package com.yc.springmvc;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.MySqlDialect;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.yc.springmvc.web.DateConvertor;
import com.yc.springmvc.web.LoginInterceptor;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@ComponentScan("com.yc")
@EnableWebMvc
@MapperScan("com.yc.springmvc.mapper")
public class MvcConfig implements WebMvcConfigurer {
//    @Override
//    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//        configurer.enable();
//    }

    // 静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations(
                        "file:D:/_文件柜/yc127_129/yc127_129/springmvc-demo/src/main/webapp/");
        // 映射文件上传web路径
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:D:/_文件柜/yc127_129/0724/");
    }

    // 文件上传解析器
    @Bean
    public StandardServletMultipartResolver multipartResolver(){
        return new StandardServletMultipartResolver();
    }

    // 用于注册转换器和数据格式化对象
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConvertor());
    }

    /* **************************************************************** */
    /*  THYMELEAF-SPECIFIC ARTIFACTS                                    */
    /*  TemplateResolver <- TemplateEngine <- ViewResolver              */
    /* **************************************************************** */

    @Resource
    ApplicationContext applicationContext;
    @Bean
    public SpringResourceTemplateResolver templateResolver(){
        // SpringResourceTemplateResolver automatically integrates with Spring's own
        // resource resolution infrastructure, which is highly recommended.
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix(
                "/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        // HTML is the default value, added here for the sake of clarity.
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // Template cache is true by default. Set to false if you want
        // templates to be automatically updated when modified.
        templateResolver.setCacheable(false);

        /**
         * 注意： 设置字符集, 不然页面中的静态文字会出现乱码！！！
         */
        templateResolver.setCharacterEncoding("utf-8");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine(){
        // SpringTemplateEngine automatically applies SpringStandardDialect and
        // enables Spring's own MessageSource message resolution mechanisms.
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        // Enabling the SpringEL compiler with Spring 4.2.4 or newer can
        // speed up execution in most scenarios, but might be incompatible
        // with specific cases when expressions in one template are reused
        // across different data types, so this flag is "false" by default
        // for safer backwards compatibility.
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Bean
    public ThymeleafViewResolver viewResolver(){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        /**
         * 注意： 设置 Content-Type ， 数据模型中的中文会乱码哟！！！
         */
        viewResolver.setContentType("text/html;charset=utf-8");
        viewResolver.setCharacterEncoding("utf-8");
        return viewResolver;
    }


    @Bean
    DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///test?useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("a");
        return dataSource;
    }
    @Bean
    MybatisSqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        /**
         * 加载 mybatis 配置 ( 可选 )
         * setConfiguration 不能和 setConfigLocation 同时使用, 否则报错
         */
        // ClassPathResource classPathResource = new ClassPathResource("mybatis.xml");
        // sqlSessionFactoryBean.setConfigLocation(classPathResource);
        /**
         * MyBatis配置类 等效于 mybatis.xml
         */
        MybatisConfiguration configuration = new MybatisConfiguration();
        /**
         * 配置日志框架 log4j, 等效于
         *
         *     "logImpl" value="LOG4J">
         *
         */
        configuration.setLogImpl(Log4jImpl.class);
        /**
         * MyBatis-Plus 分页插件
         */
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDialect(new MySqlDialect());
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        configuration.addInterceptor(mybatisPlusInterceptor);
        /**
         *  setConfiguration 不能和 setConfigLocation 同时使用, 否则报错
         */
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean;
    }

    // 拦截器注册


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/mypage.html");
    }
}
